const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { NotificationSetting } = require('../models');

/**
 * 获取通知设置
 */
const getNotificationSettings = catchAsync(async (req, res) => {
  // 通知设置一般只有一条记录，获取第一条
  let notificationSettings = await NotificationSetting.findOne({ isDeleted: false });
  
  // 如果不存在，则创建默认设置
  if (!notificationSettings) {
    notificationSettings = await NotificationSetting.create({
      adminEmail: 'admin@example.com',
    });
  }
  
  res.send(notificationSettings);
});

/**
 * 更新通知设置
 */
const updateNotificationSettings = catchAsync(async (req, res) => {
  // 通知设置一般只有一条记录，获取第一条
  let notificationSettings = await NotificationSetting.findOne({ isDeleted: false });
  
  // 如果不存在，则创建新的记录
  if (!notificationSettings) {
    notificationSettings = await NotificationSetting.create(req.body);
  } else {
    // 如果存在，则更新
    Object.assign(notificationSettings, req.body);
    await notificationSettings.save();
  }
  
  res.send(notificationSettings);
});

/**
 * 测试通知发送
 */
const testNotificationSend = catchAsync(async (req, res) => {
  const { type, method } = req.body;
  
  if (!type) {
    throw new ApiError(httpStatus.BAD_REQUEST, '请指定通知类型');
  }
  
  if (!method) {
    throw new ApiError(httpStatus.BAD_REQUEST, '请指定通知方式');
  }
  
  // 这里应该实现实际的通知发送测试逻辑
  // 例如调用邮件服务、短信服务或微信服务API
  
  res.send({
    success: true,
    message: `测试通知已发送 (类型: ${type}, 方式: ${method})`,
    timestamp: new Date(),
  });
});

module.exports = {
  getNotificationSettings,
  updateNotificationSettings,
  testNotificationSend,
}; 